package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.entity.SealTop10Flag;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.Internal;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /*
    * 营业额统计接口
    * */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getBetweenDateList(begin, end);
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnOver = orderMapper.returnOverMoneyByDay(map);
            turnoverList.add(turnOver == null ? 0.0 : turnOver);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }
    /*
    * 用户统计接口
    * */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getBetweenDateList(begin, end);
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUserTotal = userMapper.getUserTotalByDate(beginTime,endTime);
            Integer total = userMapper.getUserTotalByDate(null,endTime);
            newUserList.add(newUserTotal == null ? 0 : newUserTotal);
            totalUserList.add(total == null ? 0 : total);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
    /*
    * 订单统计接口
    * */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        Map statusMap = new HashMap();
        Integer ordersTotal = orderMapper.selectOrderStatusCount(statusMap);
        statusMap.put("status",Orders.COMPLETED);
        Integer completeOrdersTotal = orderMapper.selectOrderStatusCount(statusMap);
        List<LocalDate> dateList = getBetweenDateList(begin, end);
        List<Integer> ordersCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            Integer ordersCount = orderMapper.selectOrderStatusCount(map);
            ordersCountList.add(ordersCount);
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.selectOrderStatusCount(map);
            validOrderCountList.add(validOrderCount);

        }
        return OrderReportVO.builder()
                .totalOrderCount(ordersTotal)
                .validOrderCount(completeOrdersTotal)
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(ordersCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCompletionRate(Double.valueOf(new DecimalFormat("0.00").format(Double.valueOf((double) completeOrdersTotal /ordersTotal))))
                .build();
    }

    /*
    * 查询销量排名top10接口
    * */
    public SalesTop10ReportVO salesTop10Report(LocalDate begin, LocalDate end) {
        // SELECT order_detail.name dishId,setmealId FROM order,order_detail WHERE create_time > ? AND create_time < ? AND status = 5
        // AND order.id = order.detail.orderId;
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        map.put("status",Orders.COMPLETED);
        List<SealTop10Flag> sealTop10FlagList = orderMapper.salesTop10Flag(map);
        Map<String,Integer> resultMap = new HashMap<>();
        for (SealTop10Flag sealTop10Flag : sealTop10FlagList) {
            Long setmealId = sealTop10Flag.getSetmealId();
            Integer number = sealTop10Flag.getNumber();
            if (setmealId == null){
                String dishName = sealTop10Flag.getName();
                if (resultMap.get(dishName) == null){
                    resultMap.put(dishName,number);
                }else {
                    Integer num = resultMap.get(dishName);
                    resultMap.put(dishName, num + number);
                }
            }else{
                List<DishItemVO> dishItemVOS = setmealDishMapper.selectBySetmealIdInfo(setmealId);
                for (DishItemVO dishItemVO : dishItemVOS) {
                    String dishName = dishItemVO.getName();
                    if (resultMap.get(dishName) == null){
                        resultMap.put(dishName,dishItemVO.getCopies() * number);
                    }else {
                        resultMap.put(dishName, dishItemVO.getCopies() * number);
                    }
                }
            }
        }
        ArrayList<Map.Entry<String, Integer>> arrayList = new ArrayList<>(resultMap.entrySet());
        Collections.sort(arrayList,(a,b)->b.getValue() - a.getValue());
        List<Map.Entry<String, Integer>> entries = arrayList.subList(0, 10);
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : entries) {
            nameList.add(entry.getKey());
            numberList.add(entry.getValue());
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /*
    * 导出Excel报表接口
    * */
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.businessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充数据
            sheet.getRow(1).getCell(1).setCellValue("事件"+beginDate+ "至" +  endDate);
            // 填充概览数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessData = workspaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            // 通过输出流将EXCEL文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            // 关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static List<LocalDate> getBetweenDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        if(begin.equals(end)) dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }


}
